import React, { useEffect, useRef, useState } from 'react';
import '../../style/lyric.css';

const Musiclyric = ({ currentSong, curTim, isLyricVisible, onLyricVisibilityChange }) => {
  const [lyrics, setLyrics] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentLyricIndex, setCurrentLyricIndex] = useState(0);
  const [isUserScrolling, setIsUserScrolling] = useState(false); // 是否正在手动滚动
  const lyricContainerRef = useRef(null);
  const scrollTimeoutRef = useRef(null); // 保存定时器引用

  const toggleLyricVisibility = () => {
    onLyricVisibilityChange(!isLyricVisible)
  }

  // 获取歌词函数
  const getLyrics = async (id) => {
    try {
      const response = await fetch(`http://localhost:3000/lyric?id=${id}`);
      const data = await response.json();
      if (data && data.lrc && data.lrc.lyric) {
        return data.lrc.lyric;
      }
      throw new Error('No lyrics found');
    } catch (error) {
      console.error('Error fetching lyrics:', error);
      return '';
    }
  };

  // 解析歌词函数
  const parseLyrics = (lyricText) => {
    const lines = lyricText.split('\n');
    return lines
      .map((line) => {
        const match = line.match(/\[([0-9]{2}:[0-9]{2}\.[0-9]{2,3})\](.*)/);
        if (match) {
          const [minutes, seconds] = match[1].split(':');
          const time = parseFloat(minutes) * 60 + parseFloat(seconds);
          return { time, text: match[2].trim() };
        }
        return null;
      })
      .filter((line) => line !== null);
  };

  // 获取和解析歌词
  useEffect(() => {
    const fetchLyrics = async () => {
      setLoading(true);
      const lyricText = await getLyrics(currentSong.musicId);
      const parsedLyrics = parseLyrics(lyricText);
      setLyrics(parsedLyrics);
      setLoading(false);
    };

    if (currentSong && currentSong.musicId) {
      fetchLyrics();
    }
  }, [currentSong]);

  // 自动滚动逻辑
  useEffect(() => {
    if (curTim !== undefined && lyrics.length > 0 && !isUserScrolling) {
      const currentLyric = lyrics.find((lyric, index) => {
        return curTim >= lyric.time && (lyrics[index + 1] ? curTim < lyrics[index + 1].time : true);
      });

      if (currentLyric) {
        const currentIndex = lyrics.indexOf(currentLyric);
        setCurrentLyricIndex(currentIndex);

        if (lyricContainerRef.current) {
          const currentLyricElement = lyricContainerRef.current.children[currentIndex];
          if (currentLyricElement) {
            const containerHeight = lyricContainerRef.current.clientHeight;
            const lyricHeight = currentLyricElement.offsetHeight;
            const scrollPosition =
              currentLyricElement.offsetTop - containerHeight / 2 + lyricHeight / 2;

            lyricContainerRef.current.scrollTop = scrollPosition;
          }
        }
      }
    }
  }, [curTim, lyrics, isUserScrolling]);

  // 鼠标滚动事件监听
  useEffect(() => {
    const handleScroll = () => {
      setIsUserScrolling(true); // 用户正在手动滚动

      // 如果之前有定时器，清除它
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }

      // 设置一个新的定时器
      scrollTimeoutRef.current = setTimeout(() => {
        setIsUserScrolling(false); // 恢复自动滚动
      }, 2000); // 2 秒后恢复
    };

    const lyricContainer = lyricContainerRef.current;
    if (lyricContainer) {
      lyricContainer.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (lyricContainer) {
        lyricContainer.removeEventListener('scroll', handleScroll);
      }
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, []);

  return (
    <div className="lyric-box">
      <div className="lymaincontainer">
        <div className="downPage" onClick={toggleLyricVisibility}>
          <i className="ri-arrow-down-wide-fill"></i>
        </div>
        <div className="album-Img">
          <div className="Imgcon">
            <img src={currentSong.coverUrl} alt="" />
          </div>
        </div>
        <div className="lyric-container" >
          <div className="lyricMAIN">
            <div className="lyric-heder">
              <p>{currentSong.musicName}</p>
              <p>
                <span>{currentSong.artName}</span>
              </p>
            </div>
            <div className="lyric-main" ref={lyricContainerRef}>
              {loading ? (
                <div>Loading lyrics...</div>
              ) : lyrics.length > 0 ? (
                lyrics.map((line, index) => (
                  <div
                    key={index}
                    className={`lyric-line ${index === currentLyricIndex ? 'highlight' : ''}`}
                  >
                    {line.text}
                  </div>
                ))
              ) : (
                <div>No lyrics available</div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Musiclyric;
